.TH C++SIM 3A "23rd December 2016" "C++SIM" "C++SIM Reference Manual"
.SH NAME
Semaphore \- semaphore class
.SH SYNOPSIS
.B "#ifndef SEMAPHORE_H_"
.br
.B "#   include <Event/Semaphore.h>"
.br
.B "#endif"
.sp
.BI "class Semaphore
.br
.BI "{"
.br
.BI "public:"
.br
.BI "	enum Outcome { DONE, NOTDONE, WOULD_BLOCK };"
.sp
.BI "	Semaphore ();"
.br
.BI "	Semaphore (long number);"
.sp
.BI "	virtual ~Semaphore ();"
.sp
.BI "	virtual Semaphore::Outcome Get (Entity* attempting);"
.br
.BI "	virtual Semaphore::Outcome Release ();"
.br
.BI "	virtual Semaphore::Outcome TryGet (Entity* attempting);"
.sp
.BI "	long NumberWaiting () const;"
.br
.BI "};"
.SH DESCRIPTION
Application code can be protected from simulation processes through
semaphores, which are instances of the
.B
Semaphore
class. When creating a semaphore you can define the number of resources that are to be
protected (the default is 1). Whenever a caller tries to get the semaphore, one of the
resources will be obtained and once the number reaches 0 the next caller will be blocked
until one of the resources is releases.

A semaphore is exclusively acquired, and can exist in one of two
states:

.I
	available
: the semaphore can be acquired.

.I
	unavailable
: a process has acquired the semaphore. If another process attempts to
acquire it then it will be suspended until the semaphore is
.I
available
again.

A process attempting to acquire a semaphore should invoke the
.B
Get
method of the semaphore, passing itself as the parameter. The
process will be suspended if the semaphore cannot be acquired.

A process which successfully acquires the semaphore should
invoke its
.B
Release
method when it is no longer required. This will automatically
enable other processes to attempt to acquire the semaphore and
enter the protected region.

If the number of resources being protected by the semaphore reaches 0 then
the next attempt to Get will block the caller. If a caller does not want to
risk being blocked then it can use the
.B
TryGet
method, which will only grab a resource if one is available, otherwise if the
caller would normally block it returns immediately with the
.B
WOULD_BLOCK
code.

.B
NumberWaiting
returns the number of currently waiting (suspended) processes.
.SH NOTES
If the semaphore goes out of scope with processes still waiting
for it then an error message is displayed. No further action is
attempted on behalf of these processes.
.SH SEE ALSO
Entity(3A)
